package de.fh.ka.as.car.gui;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import de.fh.ka.as.car.util.RangeConverter;

/**
 * Slider with a value between a mininal and a maximal value;
 * 
 */
public class Slider extends GUIComponent {
	/**
	 * Converts Input: Pixel Output: range (min -max of Slider)
	 */
	protected RangeConverter range;
	protected double value;

	public enum Orientation {
		Horizontal, Vertical
	};

	protected Orientation orientation = Orientation.Vertical;

	public Slider(int x, int y, int height, int width, double min, double max, double value,
			Orientation orientation) {
		super(x, y, height, width);
		this.value = value;
		this.orientation = orientation;
		switch (orientation) {
			case Vertical:
				range = new RangeConverter(y, y + height, min, max);
				break;
			case Horizontal:
				range = new RangeConverter(x, x + width, min, max);
			default:
				break;
		}
	}

	public void setValue(double value) {
		switch (orientation) {
			case Vertical:
				this.value = range.getOutputMax() - value;
				break;
			default:
				this.value = value;
		}
		if (value < range.getOutputMin()) {
			this.value = range.getOutputMin();
		} else if (value > range.getOutputMax()) {
			this.value = range.getOutputMax();
		}
	}

	public void setValue(int px, int py) {
		if (contains(px, py)) {
			switch (orientation) {
				case Vertical:
					value = range.toOutput(py);
					break;
				case Horizontal:
					value = range.toOutput(px);
			}
			notifyListener(new SliderEvent(this, "Slided", getValue()));
		}
	}

	private void setValueVertical(int py) {
		// value = range.getOutputMax()-range.toOutput(py);

	}

	@Override
	public void draw(Canvas canvas) {
		super.draw(canvas);
		Paint paint = new Paint();
		paint.setColor(ORANGE);
		Rect rect = null;
		switch (orientation) {
			case Horizontal:
				int middle = (int) (x + (range.getInputRange() / 2));
				rect = new Rect(middle, y, (int) (range.toInput(value)), y + height);
				break;

			case Vertical:
				rect = new Rect(x, (int) range.toInput(value), x + width, y + height);
				break;
		}
		canvas.drawRect(rect, paint);
		System.out.println("");
	}

	public double getRange() {
		return range.getOutputRange();
	}

	public double getMin() {
		return range.getOutputMin();
	}

	public void setMin(double min) {
		range.setOutputMin(min);
	}

	public double getMax() {
		return range.getOutputMax();
	}

	public void setMax(double max) {
		range.setOutputMax(max);
	}

	public double getValue() {
		switch (orientation) {
			case Vertical:
				return range.getOutputMax() - value;
			default:
				return value;
		}
	}

	@Override
	public void touchEvent(int x, int y, int action) {
		if (touchEnabled) {
			setValue(x, y);
		}
	}

}
